package com.gpjcjl.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;

import com.gpjcjl.BaseLazyFragment;
import com.gpjcjl.R;
import com.gpjcjl.adapter.RecordAdapter;
import com.gpjcjl.entity.Record;
import com.gpjcjl.event.HisRecordUpdate;
import com.gpjcjl.ui.HistoryViewModel;
import com.gpjcjl.ui.RecordDetailListActivity;
import com.gpjcjl.ui.RecordUpdateActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Objects;

import butterknife.BindView;

/**
 * 已上传的原始记录
 *
 * @author yinbiao
 */
public class FragmentHisTab2 extends BaseLazyFragment implements OnItemClickListener, OnItemMenuClickListener, OnRefreshLoadMoreListener, RecordAdapter.OnItemOperateListener {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.listView)
    SwipeRecyclerView listView;
    private HistoryViewModel viewModel;

    private RecordAdapter adapter;
    private int page = 1;

    public static FragmentHisTab2 newInstance() {
        return new FragmentHisTab2();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(HisRecordUpdate event) {
        onRefresh(mRefreshLayout);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_history2, container, false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModel = new ViewModelProvider(this).get(HistoryViewModel.class);
        EventBus.getDefault().register(this);

        DividerItemDecoration divider = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(mContext, R.drawable.item_divider8)));
        listView.addItemDecoration(divider);

        listView.setOnItemClickListener(this);
        listView.setOnItemMenuClickListener(this);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);

        //        listView.setSwipeMenuCreator((leftMenu, rightMenu, position) -> {
        //            SwipeMenuItem deleteItem = new SwipeMenuItem(mContext); // 各种文字和图标属性设置。
        //            deleteItem.setText("删除")
        //                    .setWidth(160)
        //                    .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
        //                    .setTextColorResource(R.color.white)
        //                    .setBackgroundColorResource(R.color.c_FF2D55);
        //            rightMenu.addMenuItem(deleteItem); // 在Item右侧添加一个菜单。
        //        });

        listView.setAdapter(adapter = new RecordAdapter(mContext, new ArrayList<>(), false));
        adapter.setOnItemOperateListener(this);
    }

    private void initData() {
        viewModel.getRecordList(page).observe(this, result -> {
            mRefreshLayout.finishRefresh();
            mRefreshLayout.finishLoadMore();
            if (result.isSuccess()) {
                adapter.addList(result.getData(), page == 1);
                page += 1;
            }
        });
    }


    @Override
    public void onItemClick(View view, int adapterPosition) {
        Record record = adapter.getItem(adapterPosition);
        RecordDetailListActivity.startIntent(mContext, record, true);
    }

    @Override
    public void onItemClick(SwipeMenuBridge menuBridge, int position) {
        menuBridge.closeMenu();
        Record record = adapter.getItem(position);
        if (menuBridge.getPosition() == 0) {
            deleteRecord(record);
        }
    }

    private void deleteRecord(Record record) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setMessage("确认删除该原始记录？");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", (dialog, which) -> {
            showLoading();
            viewModel.delRecord(record).observe(this, result -> {
                dismissLoading();
                if (result.isSuccess()) {
                    onRefresh(mRefreshLayout);
                }
            });
        });
        builder.create().show();
    }

    @Override
    protected void onLazyLoad() {
        initData();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        initData();
    }

    @Override
    public void onUploadItem(int position) {
    }

    @Override
    public void onEditItem(int position) {
        RecordUpdateActivity.startIntent(mContext, adapter.getItem(position), true);
    }
}
